package com.totoro.controller.request;

import com.totoro.pojo.*;
import com.totoro.service.*;
import com.totoro.utils.Base64EncryptionUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author TOTORO
 * @date 2021/7/19 14:48
 */
@Controller
@RequestMapping("/order")
public class OrderRequestController {
    static Logger logger = Logger.getLogger(OrderRequestController.class);
    @Autowired
    ProductService productService;
    @Autowired
    AddressService addressService;
    @Autowired
    ShopService shopService;
    @Autowired
    CartService cartService;
    @Autowired
    OrderService orderService;
    @Autowired
    EvaluationService evaluationService;

    ProductAndBuyRequestController pab;


    /**
     * 直接购买 - 跳转至确认订单页面
     * @return
     */
    @SneakyThrows
    @RequestMapping("/confirm_order")
    public String goConfirmOrder(@RequestParam("ttr") String ttr, Model model, HttpSession session, HttpServletRequest request){
        String lastCharacter = ttr.substring(ttr.length()-1, ttr.length());
        // 如果用户篡改了地址
        if(!lastCharacter.equals("0") && !lastCharacter.equals("1")){
            return "redirect:/app/tmall/common/error.html";
        }
        int lastNumber = Integer.parseInt(lastCharacter);
        boolean isCart = lastNumber==0?false:true;
        // 将是否为购物车结账存进session中
        session.setAttribute("isCart", isCart);
        User user = (User) session.getAttribute("user");
        List<Shop> pays = (List<Shop>) session.getAttribute("pays");
        // 如果为空或者过期，返回到首页页
        if(null == pays || pays.size()<=0){
            return "redirect:/";
        }

        List<Address> addresses = addressService.findAddressByUid(user.getUserId());
        model.addAttribute("pays", pays);
        model.addAttribute("addresses", addresses);
        addresses.forEach(address -> System.out.println(address));
        return "include/buy/confirm_order";
    }


    /**
     * 跳转至结算页面
     * @return
     */
    @RequestMapping("/lightPayCashier")
    public String lightPayCashier(@RequestParam(value = "timeStamp", required = false, defaultValue = "") Long timeStamp,
                                  @RequestParam(value = "bizOrderId", required = false, defaultValue = "")String orderId, HttpSession session, Model model){
        boolean isMar = false;
        if(orderId.length() > 0){
            // 查询是否有该订单
            List<MarketOrder> marketOrders = orderService.findAllOrder(orderId, 2, 1);
            if(marketOrders.size() > 0){
                isMar = true;
                model.addAttribute("marketOrder", marketOrders.get(0));
            } else{
                return "redirect:/order/confirmOrderError.htm?errorType=TIME_OUT_10_MIN";
            }
        } else {
            // 获取购物详情的session
            PayDetails payDetails = (PayDetails) session.getAttribute("payDetails");
            if (null == payDetails) {
                return "redirect:/order/confirmOrderError.htm?errorType=TIME_OUT_10_MIN";
            }
            // 判断时间是否相同
            if (timeStamp != payDetails.getTimeStamp()) {
                return "redirect:/app/tmall/common/error.html";
            }
            model.addAttribute("payDetails", payDetails);
            session.removeAttribute("payDetails");
        }

        model.addAttribute("isMar", isMar);
        return "include/buy/pay";
    }

    /**
     * 跳转至支付成功页面
     * @param session
     * @param model
     * @return
     */
    @RequestMapping("/paySuccess")
    public String goPaySuccess(HttpSession session, Model model){
        List<MarketOrder> marketOrders = (List<MarketOrder>) session.getAttribute("orders");
        if(null == marketOrders || marketOrders.size()<1){
            return "redirect:/order/confirmOrderError.htm?errorType=TIME_OUT_10_MIN";
        }
        double allPrice = marketOrders.stream().mapToDouble(MarketOrder::getAllPrice).sum();
        model.addAttribute("allPrice", allPrice);
        session.removeAttribute("orders");
        return "include/buy/pay_success";
    }


    /**
     * 订单错误
     * @param errorType
     * @return
     */
    @RequestMapping("/confirmOrderError")
    public String confirmOrderError(@RequestParam("errorType") String errorType){
        return "include/buy/confirm_order_error";
    }


    /**
     * 确认收货页面
     * @param orderId
     * @return
     */
    @RequestMapping("/confirm_goods")
    public String confirmGoods(@RequestParam("bizOrderId") String orderId, Model model){
        // 这里是收货 ，先判断用户的订单状态是否是未收货
        MarketOrder marketOrder = orderService.findAllOrder(orderId,2, 0).get(0);
        if(marketOrder.getOrderStatus()!=3){
            return "redirect:/order/confirmOrderError.htm?errorType=ALREADY_RECEIPT";
        }
        model.addAttribute("marketOrder", marketOrder);
        return "include/buy/confirm_goods";
    }


    /**
     * go 交易成功页面，是交易成功，不是付款成功
     * @param orderId
     * @param model
     * @return
     */
    @SneakyThrows
    @RequestMapping(value = "/transaction_success")
    public String transactionSuccess(@RequestParam("bizOrderId") String orderId, @RequestParam("timeStamp") String timeStamp, Model model){
        MarketOrder marketOrder = orderService.findAllOrder(orderId,2, 0).get(0);
        if(!timeStamp.equals(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(marketOrder.getCreateTime()).getTime()+"")){
            String configCode= URLEncoder.encode("该订单出现了错误，请重新操作!","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=NOT&errorMsg="+configCode;
        }
        model.addAttribute("marketOrder", marketOrder);
        return "include/buy/transaction_success";
    }


    /**
     * 跳转至交易快照
     * @return
     */
    @RequestMapping("/tradeSnap")
    public String requestTradeSnap(@RequestParam("tradeID") String orderId, @RequestParam("detailID") int osrId,
                                   @RequestParam("snapShot") boolean snapShot, HttpSession session, Model model){
        // 根据订单ID获得主订单信息
        MarketOrder marketOrder = orderService.findAllOrder(orderId, 2, 0).get(0);
        System.out.println(marketOrder.getMarketSrOrderList());
        if(marketOrder == null){
           return "redirect:/";
        }
        User user = (User) session.getAttribute("user");
        if(user.getUserId() != marketOrder.getUser().getUserId()){
            System.out.println("哈啊啊啊啊啊啊啊啊啊啊啊啊啊啊啊");
            return "redirect:/";
        }
        // 直接从主表中拿到对应的详情记录
        MarketSrOrder marketSrOrder = null;
        for (MarketSrOrder srOrder : marketOrder.getMarketSrOrderList()) {
            if(srOrder.getId() == osrId){
                marketSrOrder = srOrder;
                break;
            }
        }
        model.addAttribute("marketSr", marketSrOrder);
        return "include/buy/transaction_snapshot";
    }


    /**
     * 跳转至发布评论页面
     * @param bizOrderId 订单号
     * @param detailID 订单详情自增键
     * @return
     */
    @SneakyThrows
    @RequestMapping("/publish_evaluation")
    public String publishEvaluation(@RequestParam("bizOrderId") String bizOrderId, @RequestParam("detailID") String detailID,
                                    @RequestParam("timeStamp") String timeStamp, Model model){
        logger.info("用户进入发布评论页面");
        MarketOrder marketOrder = orderService.findAllOrder(bizOrderId,2, 0).get(0);
        // 如果订单的创建时间和TimeStamp对不上
        String createTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(marketOrder.getCreateTime()).getTime()+"";
        if(!createTime.equals(timeStamp)){
            return "redirect:/tmall_error.htm?t=TIMESTAMP_ERROR";
        }
        // 订单必须是数字
        boolean isNunicodeDigits= StringUtils.isNumeric(detailID);
        boolean isNunicodeDigits2 = StringUtils.isNumeric(bizOrderId);
        if(!isNunicodeDigits || !isNunicodeDigits2){
            return "redirect:/tmall_error.htm?t=ORDER_NOT_NUMBER";
        }
        // 拿到整个订单，再用详情ID跟订单里的详情映射集合进行比对，如果没有该详情ID，代表是用户修改了url参数
        List<MarketSrOrder> marketSrOrders = marketOrder.getMarketSrOrderList();
        List<Integer> detailIDs = new ArrayList<>();
        marketSrOrders.forEach(v->detailIDs.add(v.getId()));
        boolean isHave = detailIDs.contains(Integer.parseInt(detailID));
        if(!isHave){
            String configCode= URLEncoder.encode("订单详情不相容","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=ORDER_DETAIL_INCOMPATIBLE="+configCode;
        }
        model.addAttribute("marketOrder", marketOrder);
        for (MarketSrOrder marketSrOrder : marketSrOrders) {
            if(marketSrOrder.getId() == Integer.parseInt(detailID)){
                model.addAttribute("marketSrOrder", marketSrOrder);
                // 如果已經評價過
                if(marketSrOrder.getIsComment() == 1){
                    String configCode= URLEncoder.encode("该订单已经评论过了","UTF-8");
                    return "redirect:/tmall_process_error.htm?errorType=ALREADY_APPEND_RATE&errorMsg="+configCode;
                }
                break;
            }
        }
        return "include/buy/publish_evaluation";
    }

    /**
     * 评论成功
     * @param brandId
     * @param model
     * @return
     */
    @RequestMapping(value = "/remarkSeller4Mall")
    public String evaluationSuccess(@RequestParam("brandID") Integer brandId, Model model){
        // 获得店铺
        Shop shop = shopService.findShopBySid(brandId);
        model.addAttribute("shop", shop);
        return "include/buy/evaluation_success";
    }

    /**
     * 追评
     * @param orderId
     * @param msroId
     * @param model
     * @return
     */
    @SneakyThrows
    @RequestMapping("/append_rate_detail")
    public String appendEvaluation(@RequestParam("trade_id") String orderId, @RequestParam("detail_id") int msroId, Model model){
        MarketOrder marketOrder = orderService.findAllOrder(orderId,2, 0).get(0);
        // 拿到该订单详情记录
        MarketSrOrder marketSrOrder = null;
        for (MarketSrOrder msOrder : marketOrder.getMarketSrOrderList()) {
            if(msOrder.getId() == msroId){
                marketSrOrder = msOrder;
            }
        }
        // 如果該訂單已經追評過，則不允許
        if(marketSrOrder.getIsAppendComment() == 1){
            String configCode= URLEncoder.encode("该订单已经追评过了","UTF-8");
            return "redirect:/tmall_process_error.htm?errorType=ALREADY_APPEND_RATE&errorMsg="+configCode;
        }
        List<ProductComment> productComments = evaluationService.findProductAllEvaluationByPid(marketSrOrder.getProduct().getId(), 0, "date");
        System.out.println(productComments);
        model.addAttribute("marketSrOrder", marketSrOrder);
        model.addAttribute("productComments", productComments);
        Product product = new Product();
        product.setId(marketSrOrder.getProduct().getId());
        model.addAttribute("product", product);
        ProductComment productComment = evaluationService.findProductEvaluationByMsId(marketSrOrder.getId());
        model.addAttribute("productComment", productComment);
        return "include/buy/append_evaluation";
    }

    /**
     * 跳转至订单详情
     * @param orderId
     * @param model
     * @return
     */
    @RequestMapping("/ticket_trade_item_detail")
    public String orderDetail(@RequestParam("tradeId") String orderId, Model model){
        // 将该订单信息传递
        MarketOrder marketOrder = orderService.findAllOrder(orderId, 2, 0).get(0);
        model.addAttribute("marketOrder", marketOrder);
        // 拿到该订单12345时间线
        Map<String, OrderTimeline> orderTimelineMap = orderService.findOrderTimeLineByMid(marketOrder.getId());
        model.addAttribute("timeLineMap", orderTimelineMap);
        return "include/buy/order_detail";
    }

    @RequestMapping("/dwa")
    public  String test(){
        return "include/user/list_bougth_items";
    }

}
